accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
expire = 0
updir = ''
picnewname = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000; 

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        serverUrl = '/template/oss_auth/wechat';
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText;
    }
    else
    {
    	common.alert("上传错误，请更换浏览器.");
    }
};

function get_signature()
{
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        updir = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
	//增加图片位置标识,
	picnewname = updir + act_id + random_string(5) + suffix;
}


function set_upload_param(up, filename, ret)
{
    if (ret == false)
    {
        ret = get_signature()
    }
    
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : picnewname,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });
   
    up.start();
}


var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : 'sharebutton', 
    //multi_selection: false,
	//container: document.getElementById('resetimg'),//生成html的form的隐藏容器.
	flash_swf_url : 'Moxie.swf',
	silverlight_xap_url : 'Moxie.xap',
    url : img_host,

    filters: {
        mime_types : [ //只允许上传图片
        { title : "Image files", extensions : "*" }
        ],
        max_file_size : '10mb', //最大只能上传10mb的文件
        prevent_duplicates : true //不允许选取重复文件
    },

	init: {
		PostInit: function() { 
			//初始化,只用于控件加载第一次,如提示控件初始化
			//$('#sharebutton').css('display','none');
			set_upload_param(uploader, '', false);
			$(".moxie-shim").attr('style','position: absolute; top: 0; left: 0; width: 80px; height: 80px; overflow: hidden;z-index:104;');
		},

		FilesAdded: function(up, files) {
			//每次图片加载都会触发
			//$('#sharebutton').css('display','inline');
			if(files[0].type=='image/jpeg' || files[0].type=='image/png' || files[0].type=='image/bmp' || files[0].type=='image/gif'){
				set_upload_param(uploader, '', false);
			}else{
				//可能不同手机检测得不到文件后缀,需要手动检测
				var divs = files[0].name.split('.');
				var real_type = divs[divs.length-1].toLowerCase();
				if(real_type == 'jpg' || real_type == 'jpeg' || real_type == 'png' || real_type == 'gif' || real_type == 'bmp' || real_type.substring(0,5)=='image'){
					set_upload_param(uploader, '', false);
				}else{
					for(var onefile in uploader.files) {
						uploader.removeFile(uploader.files[onefile].id);
					}
					common.alert('文件上传格式错误'+real_type);
				}
			}
		},

		BeforeUpload: function(up, file) {
			//点击上传时候触发
            set_upload_param(up, file.name, true);
            //设置file.name
            file.name = picnewname;
        },

		UploadProgress: function(up, file) {
			//console.log('上传:'+file.percent+'%');
		},

		FileUploaded: function(up, file, info) {
            if (info.status == 200)
            {
            	//重新设置img背景地址
            	$('#resetimg').attr('src',img_host+'/'+file.name+'?x-oss-process=style/kn900');
            	
            	mywechat.share_save(file.name);//立即保存图片
            } 
            else
            {
            	common.alert('图片上传失败');
            } 
		},

		Error: function(up, err) {
			if (err.code == -600) {
            	common.alert('您传的图片文件太大');
            }
            else if (err.code == -601) {
            	common.alert('请您上传正确的图片格式');
            }
            else if (err.code == -602) {
            	common.alert('相同图片只能上传一次');
            }
            else 
            {
            	common.alert(err.response);
            }
		}
	}
});
uploader.init();
